<template>
  <div class="cinema-page">
    <AppHeader />
    <div class="movie-banner" v-if="movieData && movieData.length > 0">
      <div class="cinema-container">
        <div class="movie-info" v-if="movieData && movieData[0]">
          <div class="poster-container">
            <img 
              :src="`${BASE_URL}${movieData[0].posterUrl}`"
              :alt="movieData[0].movieName" 
              class="movie-poster"
            >
          </div>
          <div class="movie-detail">
            <h1 class="movie-name">{{ movieData[0].movieName }}</h1>
            <div class="movie-stats">
              <div class="movie-type">{{ getGenreLabel(movieData[0].genre) }}</div>
              <div class="movie-duration">{{ movieData[0].durationMinutes }}分钟</div>
              <div class="movie-country">{{ movieData[0].country }}</div>
              <div class="movie-language">{{ movieData[0].language }}</div>
              <div class="release-time">{{ movieData[0].releaseYearDate.split(' ')[0] }} 中国大陆上映</div>
            </div>
            <div class="movie-info-rows">
              <div class="info-row">
                <span class="label">导演：</span>
                <span class="value">{{ movieData[0].director }}</span>
              </div>
              <div class="info-row">
                <span class="label">主演：</span>
                <span class="value">{{ movieData[0].cast }}</span>
              </div>
              <div class="info-row">
                <span class="label">制片国家/地区：</span>
                <span class="value">{{ movieData[0].country }}</span>
              </div>
            </div>
            <div class="movie-desc">{{ movieData[0].description }}</div>
          </div>
          <div class="movie-extra-info">
            <div class="score-container">
              <div class="score-label">猫眼口碑</div>
              <div class="score-value">{{ movieData[0].rating || '暂无' }}</div>
            </div>
            <div class="box-office">
              <div class="box-office-label">票价</div>
              <div class="box-office-value">{{ movieData[0].price }}<span class="unit">元</span></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="cinema-container main-content">
      <div class="filter-section">
        <div class="filter-group">
          <div class="filter-line">
            <div class="filter-title">区域:</div>
            <div class="filter-options">
              <span 
                class="filter-item" 
                :class="{ active: selectedArea === '全城' }"
                @click="selectArea('全城')"
              >全城</span>
              <span 
                v-for="area in areas" 
                :key="area" 
                class="filter-item"
                :class="{ active: selectedArea === area }"
                @click="selectArea(area)"
              >{{ area }}</span>
            </div>
          </div>
          <div class="filter-line">
            <div class="filter-title">影厅类型:</div>
            <div class="filter-options">
              <span 
                class="filter-item" 
                :class="{ active: selectedHallType === '全部' }"
                @click="selectHallType('全部')"
              >全部</span>
              <span 
                v-for="type in hallTypes" 
                :key="type" 
                class="filter-item"
                :class="{ active: selectedHallType === type }"
                @click="selectHallType(type)"
              >{{ type }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="cinema-list">
        <div v-for="cinema in halls" :key="cinema.id" class="cinema-item">
          <div class="cinema-main-info">
            <h3 class="cinema-name">{{ cinema.name }}</h3>
            <div class="cinema-price">
              <span class="price" v-if="movieData && movieData[0]">¥{{ movieData[0].price }}</span>
              <span class="price-text"></span>
              <button class="buy-btn" @click="handleBuy(cinema.id)">选座购票</button>
            </div>
          </div>
          <div class="cinema-address">
            <span class="address-text">{{ cinema.address }}</span>
            <span class="distance">{{ cinema.distance }}</span>
          </div>
          <div class="cinema-hall-names">
            <span class="hall-name">
              {{ cinema.hallName }}
            </span>
          </div>
          <div class="cinema-tags">
            <span v-if="cinema.hasImax" class="tag">IMAX厅</span>
            <span v-if="cinema.has3d" class="tag">3D</span>
            <span v-if="cinema.hasVip" class="tag">VIP厅</span>
            <span v-for="(tag, index) in cinema.tags" :key="index" class="tag">{{ tag }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import AppHeader from '@/components/AppHeader.vue'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'

const route = useRoute()
const router = useRouter()
const locationInfo = inject('locationInfo')
const areas = ref([])
const selectedArea = ref('全城')
const movieData = ref([])
const hallTypes = ref(['IMAX厅', 'CGS中国巨幕厅', '杜比全景声厅', 'RealD厅', '4DX厅', 'DTS:X 临境音厅', '儿童厅', '4K厅', '4D厅', '60帧厅', '巨幕厅', '激光厅'])
const selectedHallType = ref('全部')

// 获取路由参数中的电影信息
const movieId = ref(route.query.movieId)

// 获取电影详细信息
const getMovieDetail = async () => {
  if (!movieId.value) {
    console.warn('没有获取到电影ID')
    return
  }

  try {
    console.log('开始获取电影详情, movieId:', movieId.value)
    const response = await axios.get(`${BASE_URL}/v1/movie/select`, {
      params: {
        id: movieId.value
      }
    })
    
    if (response.data.code === 2000) {
      if (response.data.data?.list && response.data.data.list.length > 0) {
        movieData.value = response.data.data.list
        console.log('电影详情获取成功:', movieData.value)
      } else {
        console.warn('电影详情数据为空')
      }
    } else {
      throw new Error(response.data.msg || '获取电影详情失败')
    }
  } catch (error) {
    console.error('获取电影详情失败:', error)
  }
}


// 获取城市的区域列表
const fetchCityAreas = async (city) => {
  
  try {
    // 使用高德地图 API 获取区域数据
    const response = await axios.get('https://restapi.amap.com/v3/config/district', {
      params: {
        keywords: city,
        subdistrict: 1,
        key: '57767578b7f25b7c37380e11b5e55ff7'
      }
    })
    
    const { data } = response
    
    if (data.status === '1' && data.districts && data.districts[0] && data.districts[0].districts) {
      // 从返回数据中提取区域名称
      const districts = data.districts[0].districts
        .map(d => d.name)
        .filter(name => name.includes('区') || name.includes('县') || name.includes('市'))
      

      
      if (districts.length > 0) {
        areas.value = districts
        return districts
      }
    }
    
    // 如果 API 调用失败或没有数据，使用预设数据
    const presetDistricts = getPresetDistricts(city)

    areas.value = presetDistricts
    
  } catch (error) {
   
    const presetDistricts = getPresetDistricts(city)
   
    areas.value = presetDistricts
  }
}

// 区域选择处理函数
const selectArea = (area) => {
  selectedArea.value = area
  searchCinemaForm.value.address = area
  selectCinemaByHallTypeAndCityAndPlanMovieId()
}
const selectHallType = (type) => {
  selectedHallType.value = type
  searchCinemaForm.value.type = type
  selectCinemaByHallTypeAndCityAndPlanMovieId()
}

// 预设的城市区域数据（作为备选）
const presetDistrictsMap = {
  '太原': ['小店区', '迎泽区', '杏花岭区', '尖草坪区', '万柏林区', '晋源区', '清徐县', '阳曲县', '娄烦县', '古交市'],
  '北京': ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区'],
  '上海': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '闵行区', '宝山区', '嘉定区', '浦东新区', '金山区', '松江区', '青浦区', '奉贤区', '崇明区'],
  '广州': ['越秀区', '海珠区', '荔湾区', '天河区', '白云区', '黄埔区', '花都区', '番禺区', '南沙区', '从化区', '增城区'],
  '深圳': ['福田区', '罗湖区', '南山区', '盐田区', '宝安区', '龙岗区', '龙华区', '坪山区', '光明区']
}

// 获取预设的区域数��
const getPresetDistricts = (city) => {
  const cityName = city.replace(/市$/, '')
  const key = Object.keys(presetDistrictsMap).find(k => 
    k === cityName || k.replace(/市$/, '') === cityName
  )
  return key ? presetDistrictsMap[key] : []
}

// 监听城市变化
watch(locationInfo, async (newCity) => {
  if (newCity && typeof newCity === 'string' && newCity !== '正在解析位置信息...') {
    console.log('检测到城市信息(字符串):', newCity)
    await fetchCityAreas(newCity)
  }
}, { immediate: true })

// 电影类型字典
const genreDict = {
  10: '恐怖',
  20: '动作',
  30: '悬疑',
  40: '科幻',
  50: '动画',
  60: '惊悚',
  70: '战争',
  80: '喜剧',
  90: '爱情',
  100: '剧情',
  110: '犯罪',
  120: '冒险',
  130: '奇幻',
  140: '音乐',
  150: '历史',
  160: '传记',
  170: '歌舞'
}

// 获取类型标签的方法
const getGenreLabel = (value) => {
  return genreDict[value] || '未知类型'
}
const halls = ref([])
const searchCinemaForm = ref({
  movieId: movieId.value,
  address: '全城',
  type: '全部'
})


// 添加影厅类型选择处理函数
const selectCinemaByHallTypeAndCityAndPlanMovieId = () => {
  const params = {
    movieId: movieId.value,
  }
  
  // 只有当不是"全城"时才添加地址参数
  if (searchCinemaForm.value.address && searchCinemaForm.value.address !== '全城') {
    params.address = searchCinemaForm.value.address
  }
  
  // 只有当不是"全部"时才添加类型参数
  if (searchCinemaForm.value.type && searchCinemaForm.value.type !== '全部') {
    params.type = searchCinemaForm.value.type
  }
  
  const queryString = qs.stringify(params)
  console.log("查询条件：", params)
  
  axios.get(`${BASE_URL}/v1/cinemas/selectCinemaByHallTypeAndCityAndPlanMovieId?${queryString}`)
    .then((response) => {
      if (response.data.code === 2000) {
        console.log("后端返回的原始影院数据：", response.data.data)
        const uniqueHalls = Array.from(new Set(response.data.data.map(JSON.stringify))).map(JSON.parse)
        console.log("去重后的影院数据：", uniqueHalls)
        halls.value = uniqueHalls
      } else {
        ElMessage.error(response.data.msg || '获取影厅列表失败')
      }
    })
}

// 修改购票处理函数
const handleBuy = (cinemaId) => {
  // 直接跳转到影院详情页面
  router.push({
    name: 'cinema-detail',
    params: { id: cinemaId },
    query: {
      movieId: movieId.value  // 传递电影ID
    }
  })
}
onMounted(() => {
  getMovieDetail()
  selectArea('全城')
  selectHallType('全部')
  selectCinemaByHallTypeAndCityAndPlanMovieId()
})
</script>

<style scoped>
.cinema-page {
  background: #f4f4f4;
  min-height: 100vh;
}

.movie-banner {
  background: linear-gradient(to right, #2b2b3c 0%, #1c1c28 100%);
  padding: 40px 0;
}

.cinema-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.movie-info {
  display: flex;
  gap: 30px;
  color: #fff;
}

.poster-container {
  flex-shrink: 0;
}

.movie-poster {
  width: 240px;
  height: 330px;
  border-radius: 4px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
}

.movie-detail {
  flex: 1;
  padding-top: 10px;
}

.movie-name {
  font-size: 26px;
  margin: 0;
  font-weight: bold;
}

.movie-name-en {
  font-size: 18px;
  margin: 8px 0 20px;
  font-weight: normal;
  opacity: 0.8;
}

.movie-stats {
  font-size: 14px;
  line-height: 1.8;
  opacity: 0.9;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  gap: 15px;
}

.btn-want,
.btn-score {
  padding: 8px 24px;
  border-radius: 20px;
  border: none;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-want {
  background: #ff5f16;
  color: white;
}

.btn-score {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}

.main-content {
  padding-top: 20px;
}

.filter-section {
  background: #fff;
  border-radius: 4px;
  padding: 0;
}

.filter-line {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-title {
  color: #333;
  font-size: 14px;
  width: 80px;
}

.filter-options {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-item {
  padding: 6px 15px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  border-radius: 15px;
  transition: all 0.2s;
}

.filter-item:hover {
  color: #ff5f16;
}

.filter-item.active {
  background: #ff5f16;
  color: #fff;
}

@media (max-width: 768px) {
  .movie-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .action-buttons {
    justify-content: center;
  }

  .filter-line {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-title {
    margin-bottom: 10px;
  }
}

.cinema-list {
  margin-top: 20px;
}

.cinema-item {
  background: #fff;
  padding: 20px;
  margin-bottom: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.cinema-main-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.cinema-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.cinema-price {
  display: flex;
  align-items: center;
  gap: 10px;
}

.price {
  color: #ff5f16;
  font-size: 20px;
  font-weight: bold;
}

.price-text {
  color: #999;
  font-size: 14px;
}

.buy-btn {
  background: #ff5f16;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 15px;
  cursor: pointer;
  font-size: 14px;
}

.cinema-address {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.distance {
  color: #999;
}

.cinema-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  padding: 2px 8px;
  background: #f5f5f5;
  color: #666;
  font-size: 12px;
  border-radius: 2px;
}

.cinema-hall-names {
  margin: 8px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.hall-name {
  padding: 4px 10px;
  background: #f0f7ff;
  color: #1890ff;
  font-size: 13px;
  border-radius: 4px;
}
</style> 